package com.tgy.servlet.user;

import com.alibaba.fastjson.JSONArray;
import com.mysql.cj.util.StringUtils;
import com.tgy.entity.Role;
import com.tgy.entity.SmbmsUser;
import com.tgy.service.role.RoleServiceImpl;
import com.tgy.service.user.UserService;
import com.tgy.service.user.userServiceImpl.UserServiceImpl;
import com.tgy.utils.Constant;
import com.tgy.utils.PageSupport;
import org.junit.Test;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/***
 * @ClassName: UserServlet
 * @Description:
 * @Auther: 送一一块二向箔
 * @Date: 11:47 2021/12/10
 * @version : V1.0
 */
public class UserServlet extends HttpServlet {
    //实现Servlet复用
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String method = req.getParameter("method");
        switch (method) {
            case "savepwd":
                this.pwdUpdate(req, resp);
                break;
            case "pwdmodify":
                this.pwdmodify(req, resp);
                break;
            case "query":
                this.userQuery(req, resp);
                break;
            case "add":
                this.userAdd(req, resp);
                break;
        }
    }
/**
 * @Param  修改密码的Servlet
 * @Description:
 * @auther: TangGuoyi
 * @date: 15:26 2021/12/10
 * @return:
 */
    private void pwdUpdate(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        boolean flag =false;
        Object attribute = req.getSession().getAttribute(Constant.USER_SESSION);
        String newpassword = req.getParameter("newpassword");
        if (attribute!=null && !StringUtils.isNullOrEmpty(newpassword)){
            UserService userService = new UserServiceImpl();
            flag = userService.updPassword(((SmbmsUser) attribute).getUserCode(), newpassword);
            if (flag) {
                req.setAttribute(Constant.MESSAGE, "密码修改成功！");
                req.getSession().removeAttribute(Constant.USER_SESSION);
                //resp.sendRedirect(req.getContextPath()+"/login.jsp");
            }else{
                req.setAttribute(Constant.MESSAGE, "密码修改失败！");
            }
        }else {
            req.setAttribute(Constant.MESSAGE, "密码格式问题失败！");
        }
        //req.getRequestDispatcher("pwdmodify.jsp").forward(req, resp);
        resp.sendRedirect(req.getContextPath()+"/login.jsp");
    }

    /**
     * @Param 验证旧密码
     * @Description:
     * @auther: TangGuoyi
     * @date: 15:32 2021/12/10
     * @return:
     */
    private void pwdmodify(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        //得到session
        Object attribute = req.getSession().getAttribute(Constant.USER_SESSION);
        String oldpassword = req.getParameter("oldpassword");
        //万能的map
        HashMap<String, String> resultMap = new HashMap<>();
        if(attribute == null){//session过期
            resultMap.put("result","sessionerror");
        }else if (StringUtils.isNullOrEmpty(oldpassword)) {
            //输入为空
            resultMap.put("result", "error");
        } else {
            //获取Session中的用户密码
            String userPassword = ((SmbmsUser) attribute).getUserPassword();
            //判断输入的旧密码是否与当前Session中的密码一致
            if (oldpassword.equals(userPassword)) {
                resultMap.put("result", "true");
            } else {
                resultMap.put("result", "false");
            }
        }
        try {
            resp.setContentType("application/json");
            PrintWriter writer = resp.getWriter();
            //JSONArray:阿里巴巴的JSON工具类，转换格式
            /* resultMap=["result", "true","result", "false"]
               Json格式={key:value}
            * */
            writer.write(JSONArray.toJSONString(resultMap));
            writer.flush();
            writer.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * @Param 查询方法
     * @Description:
     * @auther: TangGuoyi
     * @date: 14:24 2021/12/11
     * @return:
     */
    private void userQuery(HttpServletRequest req, HttpServletResponse resp){
        //查询用户列表
        String queryUserName = req.getParameter("queryname");
        String temp = req.getParameter("queryUserRole");
        String pageIndex = req.getParameter("pageIndex");
        int queryUserRole = 0;

        //获取用户列表
        UserServiceImpl userService = new UserServiceImpl();

        //第一次走这个请求，一定是第一页，页面大小固定的
        //可用把pageSize写道配置文件，方便后期修改
        int pageSize = 5;
        int currentPageNo = 1;

        if (queryUserName == null) {
            queryUserName = "";
        }
        if (temp != null && !temp.equals("")) {
            //给查询赋值 0，1，2，3，
            queryUserRole = Integer.parseInt(temp);
        }
        if (pageIndex != null) {
            currentPageNo = Integer.parseInt(pageIndex);
        }

        //获取用户数量
        int totalCount = userService.getUserByLimit(queryUserName, queryUserRole);
        List<SmbmsUser> userList = null;

        //总页数支持
        PageSupport pageSupport = new PageSupport();
        pageSupport.setCurrentPageNo(currentPageNo);
        pageSupport.setPageSize(pageSize);
        pageSupport.setTotalCount(totalCount);


        //最大页数，总共有几页【如果totalCount刚好是pageSize的整数倍，那么是不是多算了一页】
        int totalPageCount = ((int) (totalCount / pageSize)) + 1;

        //控制首页和尾页
        if (currentPageNo < 1) {
            //如果页面小于第一页，就显示第一页
            currentPageNo = 1;
        } else if (currentPageNo > totalPageCount) {
            //如果页面大于最后一页，就显示最后一页
            currentPageNo = totalPageCount;
        }

        //获取用户列表展示
        userList = userService.getUserList(queryUserName, queryUserRole, currentPageNo, pageSize);
        req.setAttribute("userList", userList);

        //获取角色列表
        RoleServiceImpl roleService = new RoleServiceImpl();
        List<Role> roleList = roleService.getRoleList();

        req.setAttribute("roleList", roleList);
        req.setAttribute("totalCount", totalCount);
        req.setAttribute("currentPageNo", currentPageNo);
        req.setAttribute("totalPageCount", totalPageCount);
        req.setAttribute("queryUserName", queryUserName);
        req.setAttribute("queryUserRole", queryUserRole);

        //返回前端
        try {
            req.getRequestDispatcher("userlist.jsp").forward(req, resp);
        } catch (ServletException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    /**
     * @Param 增加用户
     * @Description:
     * @auther: TangGuoyi
     * @date: 15:18 2021/12/11
     * @return:
     */
    private void userAdd(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
        //获取输入的用户参数
        String userCode = req.getParameter("userCode");
        String userName = req.getParameter("userName");
        String userPassword = req.getParameter("userPassword");
        String gender = req.getParameter("gender");
        String birthday = req.getParameter("birthday");
        String phone = req.getParameter("phone");
        String address = req.getParameter("address");
        String userRole = req.getParameter("userRole");

        //创建一个User对象，并且根据表单获取的内容设置其属性值
        SmbmsUser user = new SmbmsUser();
        user.setUserCode(userCode);
        user.setUserName(userName);
        user.setUserPassword(userPassword);
        user.setAddress(address);
        try {
            user.setBirthday(new SimpleDateFormat("yyyy-MM-dd").parse(birthday));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        user.setGender(Integer.valueOf(gender));
        user.setPhone(phone);
        user.setUserRole(Integer.valueOf(userRole));
        user.setCreationDate(new Date());
        user.setCreatedBy(((SmbmsUser) req.getSession().getAttribute(Constant.USER_SESSION)).getId());
        //调用Service层的方法
        UserService userService = new UserServiceImpl();
        if (userService.add(user)) {
            resp.sendRedirect(req.getContextPath() + "/jsp/user.do?method=query");
        } else {
            req.getRequestDispatcher("useradd.jsp").forward(req, resp);
        }

    }
}
